package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.AuditClaim;
import com.xmy.cultivate.entity.AuditPhoto;
import com.xmy.cultivate.entity.TeacherPoint;
import com.xmy.cultivate.respons.FlowDetailRs;
import com.xmy.cultivate.respons.FlowRs;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 报销申请 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-01-01
 */
@RestController
@RequestMapping("/api/auditClaim")
public class AuditClaimController extends BaseController {
    @Autowired
    IAuditClaimService iAuditClaimService;

    @Autowired
    IAuditPhotoService iAuditPhotoService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    IOssUploadService iOssUploadService;

    @Autowired
    IDepartmentService iDepartmentService;

    @Autowired
    IAuditFlowService iAuditFlowService;

    private static final String ALLOWED_EXTENSIONS = ".jpg,.jpeg,.png,.gif";

    //上传文件保存的本地目录，使用@Value获取全局配置文件中配置的属性值，如 E:/wmx/uploadFiles/
    @Value("${uploadFile.location}")
    private String uploadFileLocation;

    @Value("${aliyun.oss.showImgEndpoint}")
    String showImgEndpoint;


    @GetMapping("/getHomeList")
    @ApiOperation("获取首页数据")
    public Result getHomeList() {
        // 判断是否为管理员，如果不是管理员，只能看跟自己相关的数据
        String adminId = String.valueOf(this.adminId);
        if (this.adminId.equals(1568138350324350975L)) {
            adminId = "0";
        }

        AuditClaim auditClaim = iAuditClaimService.getAuditClaimCount(adminId);

        return new Result(Code.OK, auditClaim, Code.GET_OK_MSG);
    }


    @GetMapping("/getClaimList")
    @ApiOperation("获取申请列表")
    public Result getAuditClaimList(
            @RequestParam(value = "pageNum", defaultValue = "-1", required = false) Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "-1", required = false) Integer pageSize,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "schoolId", required = false) String schoolId,
            @RequestParam(value = "status", required = false) String status,// 1：待处理，2：已处理，3：已发起 4：我收到的
            @RequestParam(value = "type", required = false) String type// 1：报销申请，2：付款申请，3：备用金申请，4：学员退费申请
    ) {
        // 判断是否为管理员，如果不是管理员，只能看跟自己相关的数据
        String adminId = String.valueOf(this.adminId);
        if (this.adminId.equals(1568138350324350975L)) {
            adminId = "0";
        }

        IPage<AuditClaim> iPage = new Page<>(pageNum, pageSize);

        startDate = startDate + " 00:00:00";
        endDate = endDate + " 23:59:59";

        List<AuditClaim> auditClaimList = iAuditClaimService.getAuditClaimList(iPage, schoolId, name, startDate, endDate, type, status, adminId);

        for (AuditClaim auditClaim : auditClaimList) {
            if (auditClaim.getStatus().equals(0)) {
                FlowDetailRs flowDetailRs = iAuditFlowService.getFlowTaskForDetail(auditClaim.getId());
                auditClaim.setFlowDetailList(flowDetailRs.getFlowRsList());
                auditClaim.setStayCheckNameList(flowDetailRs.getStayCheckNameList());
            }
        }

        return new Result(Code.OK, auditClaimList, Code.GET_OK_MSG);
    }


    @GetMapping("/getClaimListDetail")
    @ApiOperation("获取申请详情")
    public Result getAuditClaimDetail(@RequestParam(value = "id", required = false, defaultValue = "") String id) {
        AuditClaim auditClaim = iAuditClaimService.getAuditClaimDetail(id);

        // 获取图片
        List<AuditPhoto> auditPhotos = iAuditPhotoService.list(new QueryWrapper<AuditPhoto>().eq("sourse_id", auditClaim.getId()));
        auditClaim.setImageList(auditPhotos);
        FlowDetailRs flowDetailRs = iAuditFlowService.getFlowTaskForDetail(auditClaim.getId());
        auditClaim.setFlowDetailList(flowDetailRs.getFlowRsList());
        auditClaim.setStayCheckNameList(flowDetailRs.getStayCheckNameList());

        return new Result(Code.OK, auditClaim, Code.GET_OK_MSG);
    }


    @PostMapping("/expenseClaim")
    @ApiOperation("提交报销申请")
    public Result saveExpenseClaim(@RequestParam Map<String, String> map,
                                   @RequestParam("invoiceImgList") List<MultipartFile> invoiceImgList, // 发票图片
                                   @RequestParam("screenImgList") List<MultipartFile> screenImgList // 屏幕图片（截图）
    ) {

        String schoolId = map.get("schoolId");
        String departId = map.get("departId");
        String subjectsId = map.get("subjectsId");
        String applyId = map.get("applyId");
        String claimDate = map.get("claimDate");
        String receivableAccountId = map.get("receivableAccountId");
        String clainmType = map.get("clainmType");
        String clainmTypeName = map.get("clainmTypeName");
        String costDetail = map.get("costDetail");
        String clainmMoney = map.get("clainmMoney");
        String isHasInvoice = map.get("isHasInvoice");
        String type = map.get("type");

        AuditClaim auditClaim = new AuditClaim();
        auditClaim.setId(idWorker.nextId());
        if (StringUtils.isNotBlank(schoolId)) {
            auditClaim.setSchoolId(Long.valueOf(schoolId));
        }
        if (StringUtils.isNotBlank(departId)) {
            auditClaim.setDepartId(Long.valueOf(departId));
        }
        if (StringUtils.isNotBlank(subjectsId)) {
            auditClaim.setSubjectsId(Long.valueOf(subjectsId));
        }
        if (StringUtils.isNotBlank(applyId)) {
            auditClaim.setApplyId(Long.valueOf(applyId));
        }
        if (StringUtils.isNotBlank(claimDate)) {
            auditClaim.setClaimDate(LocalDate.parse(claimDate));
        }
        if (StringUtils.isNotBlank(receivableAccountId)) {
            auditClaim.setReceivableAccountId(Long.valueOf(receivableAccountId));
        }
        if (StringUtils.isNotBlank(clainmType)) {
            auditClaim.setClainmType(Integer.valueOf(clainmType));
        }
        if (StringUtils.isNotBlank(clainmTypeName)) {
            auditClaim.setClainmTypeName(clainmTypeName);
        }
        if (StringUtils.isNotBlank(costDetail)) {
            auditClaim.setCostDetail(costDetail);
        }
        if (StringUtils.isNotBlank(clainmMoney)) {
            auditClaim.setClainmMoney(new BigDecimal(clainmMoney));
        }
        if (StringUtils.isNotBlank(isHasInvoice)) {
            auditClaim.setIsHasInvoice(Integer.valueOf(isHasInvoice));
        }
        if (StringUtils.isNotBlank(type)) {
            auditClaim.setType(Integer.valueOf(type));
        }
        auditClaim.setCreatedId(this.adminId);
        auditClaim.setFlowId(1568138350324350901L);
        iAuditClaimService.save(auditClaim);

        try {
            LocalDate localDate = LocalDate.now();
            // 上传发票图片
            if (!invoiceImgList.isEmpty() && invoiceImgList.size() > 0) {
                String invoiceName = "auditClaim-invoice-image" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();
                String invoiceUrl = uploadFileLocation + "/" + invoiceName;

                File certificateFile = new File(invoiceUrl);
                if (!certificateFile.exists()) {
                    certificateFile.mkdirs();
                }
                for (MultipartFile image : invoiceImgList) {
                    // 获取上传文件的后缀名
                    String imageType = image.getOriginalFilename().substring(image.getOriginalFilename().indexOf("."));
                    if (imageType == null || !ALLOWED_EXTENSIONS.contains(imageType.substring(imageType.lastIndexOf(".")))) {
                        return new Result(Code.ERROR, null, "发票图片不支持该类型，请重新上传");
                    }
                    String imageDate = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
                    String imageUuid = imageDate + System.currentTimeMillis();
                    String imageFilename = "invoice-image_" + imageUuid + imageType;
                    // 完成文件上传
                    image.transferTo(new File(invoiceUrl, imageFilename));
                    String filePath = invoiceUrl + "/" + imageFilename;
                    // 上传阿里云
                    boolean upImage = iOssUploadService.upFile(filePath, imageFilename, invoiceName);
                    if (!upImage) {
                        return new Result(Code.ERROR, null, "发票图片上传失败");
                    }
                    // 保存发票图片
                    AuditPhoto auditPhoto = new AuditPhoto();
                    auditPhoto.setId(idWorker.nextId());
                    auditPhoto.setSourseId(auditClaim.getId());
                    auditPhoto.setType(Integer.valueOf(type));
                    auditPhoto.setImageType(1);
                    auditPhoto.setImageFullPath(showImgEndpoint + '/' + invoiceName + '/' + imageFilename);
                    auditPhoto.setImagePath(invoiceName + '/' + imageFilename);
                    iAuditPhotoService.save(auditPhoto);
                }
            }

            // 上传截图图片
            if (!screenImgList.isEmpty() && screenImgList.size() > 0) {
                String screenName = "auditClaim-screen-image" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();
                String screenUrl = uploadFileLocation + "/" + screenName;

                File certificateFile = new File(screenUrl);
                if (!certificateFile.exists()) {
                    certificateFile.mkdirs();
                }
                for (MultipartFile image : screenImgList) {
                    // 获取上传文件的后缀名
                    String imageType = image.getOriginalFilename().substring(image.getOriginalFilename().indexOf("."));
                    if (imageType == null || !ALLOWED_EXTENSIONS.contains(imageType.substring(imageType.lastIndexOf(".")))) {
                        return new Result(Code.ERROR, null, "截图不支持该类型，请重新上传");
                    }
                    String imageDate = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
                    String imageUuid = imageDate + System.currentTimeMillis();
                    String imageFilename = "screen-image_" + imageUuid + imageType;
                    // 完成文件上传
                    image.transferTo(new File(screenUrl, imageFilename));
                    String filePath = screenUrl + "/" + imageFilename;
                    // 上传阿里云
                    boolean upImage = iOssUploadService.upFile(filePath, imageFilename, screenName);
                    if (!upImage) {
                        return new Result(Code.ERROR, null, "截图上传失败");
                    }
                    // 保存截图
                    AuditPhoto auditPhoto = new AuditPhoto();
                    auditPhoto.setId(idWorker.nextId());
                    auditPhoto.setSourseId(auditClaim.getId());
                    auditPhoto.setType(Integer.valueOf(type));
                    auditPhoto.setImageType(2);
                    auditPhoto.setImageFullPath(showImgEndpoint + '/' + screenName + '/' + imageFilename);
                    auditPhoto.setImagePath(screenName + '/' + imageFilename);
                    iAuditPhotoService.save(auditPhoto);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 添加实例流程
        iAuditFlowService.addFlowTask(auditClaim.getId(), auditClaim.getFlowId(), auditClaim.getSchoolId(), auditClaim.getDepartId(), adminId);

        return new Result(Code.OK, "", "提交成功");
    }

    @PostMapping("/completeTask")
    @ApiOperation("审批")
    public Result completeTask(@RequestBody Map<String, String> reMap) {

        String sourseId = reMap.get("sourseId");// 审批实例id
        String teacherId = reMap.get("teacherId");// 审批老师id
        String status = reMap.get("status");// 1同意，2拒绝
        Result rs = null;
        if (status.equals("1")) {
            rs = iAuditFlowService.completeTask(Long.valueOf(sourseId), Long.valueOf(teacherId));
        } else if (status.equals("2")) {
            rs = iAuditFlowService.refuseTask(Long.valueOf(sourseId), Long.valueOf(teacherId));
        }
        return rs;
    }


}
